# -*- coding: utf-8 -*-
# @Time    : 2021/11/2 16:18
# @Author  : huangwei
# @File    : excel_method.py
# @Software: PyCharm
import cv2
import numpy as np
from openpyxl import Workbook
from openpyxl.styles import Side, PatternFill
from openpyxl.styles import Border


def get_center_point( points ):
    """ 传入四个点求中点"""
    x = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4
    y = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4

    return x, y


def word_and_box( box, word_boxes, det_words, used_index ):
    x1, y1, x2, y2, x3, y3, x4, y4 = box
    x_list = [x1, x2, x3, x4]
    y_list = [y1, y2, y3, y4]
    x_min, x_max, y_min, y_max = np.min(x_list), np.max(x_list), np.min(y_list), np.max(y_list)

    word_list = []
    c_y = []
    c_x = []

    for i in range(len(word_boxes)):
        if i not in used_index:
            center_x, center_y = get_center_point(word_boxes[i])
            if x_min < center_x < x_max and y_min < center_y < y_max:
                c_y.append(center_y)
                c_x.append(center_x)
                word_list.append(det_words[i])
                used_index.append(i)

    if len(word_list) == 1:
        return np.array(word_list)

    # 从上到下排序
    c_y = np.array(c_y)
    c_x = np.array(c_x)
    sorted_index = np.argsort(c_y)
    c_y = c_y[sorted_index]
    c_x = c_x[sorted_index]

    # for

    # 从左往右排序

    word_list = np.array(word_list)
    word_list = word_list[sorted_index]

    return word_list


def get_rotate_crop_image( img, points ):
    """
    旋转切割图片
    img_height, img_width = img.shape[0:2]
    left = int(np.min(points[:, 0]))
    right = int(np.max(points[:, 0]))
    top = int(np.min(points[:, 1]))
    bottom = int(np.max(points[:, 1]))
    img_crop = img[top:bottom, left:right, :].copy()
    points[:, 0] = points[:, 0] - left
    points[:, 1] = points[:, 1] - top
    """
    img_crop_width = int(
        max(
            np.linalg.norm(points[0] - points[1]),
            np.linalg.norm(points[2] - points[3])))
    img_crop_height = int(
        max(
            np.linalg.norm(points[0] - points[3]),
            np.linalg.norm(points[1] - points[2])))
    pts_std = np.float32([[0, 0], [img_crop_width, 0],
                          [img_crop_width, img_crop_height],
                          [0, img_crop_height]])
    M = cv2.getPerspectiveTransform(points, pts_std)
    dst_img = cv2.warpPerspective(
        img,
        M, (img_crop_width, img_crop_height),
        borderMode=cv2.BORDER_REPLICATE,
        flags=cv2.INTER_CUBIC)
    dst_img_height, dst_img_width = dst_img.shape[0:2]
    if dst_img_height * 1.0 / dst_img_width >= 1.5:
        dst_img = np.rot90(dst_img)
    return dst_img


# 得到分层分列图，移动线条
def split_floors( row_lines, col_lines, alph=5 ):
    """
    划分分成多少行和多少列,便于对应进excel中
    :param row_lines:
    :param col_lines:
    :param alph:
    :return:
    """
    # 判断竖线的条数，即分成多少列
    # 从左到右排序了，计算x轴距离
    # 向左合并，即将另一条线左移
    col_num = len(col_lines)

    col_index = [0]

    lcx = col_lines[0][0]
    x_index = [lcx]

    for i in range(col_num - 1):
        line1 = col_lines[i]
        line2 = col_lines[i + 1]

        cx1 = line1[0]

        x3, y3, x4, y4 = line2
        cx2 = line2[0]

        dis = abs(cx1 - cx2)

        if dis < alph:
            col_index.append(col_index[-1])
            print("左移第{}条线！".format(i + 1))
            x3 = x3 - dis
            x4 = x4 - dis
            line2 = [x3, y3, x4, y4]
            col_lines[i + 1] = line2
        else:
            col_index.append(col_index[-1] + 1)
            x_index.append(cx2)

    # 同理得到y的每一层
    y_index = []
    for line in row_lines:
        cy = line[1]
        y_index.append(cy)

    return x_index, y_index, row_lines, col_lines


def box_index( xy, xy_index, start ):
    min_dis = abs(xy_index[start] - xy)
    min_index = start

    # 找到最贴近的横线或竖线
    for m in range(start + 1, len(xy_index)):
        dis = abs(xy_index[m] - xy)
        if dis < min_dis:
            min_dis = dis
            min_index = m
        else:
            break
    return min_index


# 得到每一个表格框的信息 [x, y, w, h, txt]
def get_table_box_data( filepath, text_recognizer, table_boxes, word_boxes, det_word, x_index, y_index ):
    img = cv2.imread(filepath)
    box_infos = []
    used_index = []

    for table_box in table_boxes:
        x1, y1, x2, y2, x3, y3, x4, y4 = table_box[:8]

        # 左边竖线中心
        left_x = (x1 + x4) / 2
        # 找到最贴近的竖线
        box_left_index = box_index(left_x, x_index, 0)

        # 同理找另外几条线
        # 上边横线
        up_y = (y1 + y2) / 2
        box_up_index = box_index(up_y, y_index, 0)

        # 右边竖线
        right_x = (x2 + x3) / 2
        box_right_index = box_index(right_x, x_index, box_left_index)

        # 下边横线
        down_y = (y3 + y4) / 2
        box_down_index = box_index(down_y, y_index, box_up_index)

        result = ''

        word_list = word_and_box(table_box, word_boxes, det_word, used_index)

        for word in word_list:
            result = result + " " + word[0]

        location = [box_left_index, box_up_index, box_right_index - box_left_index, box_down_index - box_up_index,
                    result]
        # print("location:", location)
        box_infos.append(location)

    return box_infos


def write_excel( box_infos, x_index, y_index, output_path ):
    sheet_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'O', 'P', 'Q']

    book = Workbook()
    sheet = book.active

    for p in range(len(y_index) - 1):
        for k in range(len(x_index) - 1):
            sheet.cell(p + 1, k + 1).border = Border(top=Side(border_style='thin', color='FF000000'),
                                                     right=Side(border_style='thin', color='FF000000'),
                                                     bottom=Side(border_style='thin', color='FF000000'),
                                                     left=Side(border_style='thin', color='FF000000'))
            sheet.cell(p + 1, k + 1).fill = PatternFill("solid", fgColor="E1FFFF")
            # sheet.cell(p + 1, k + 1).value = 'a'

    for tt in box_infos:
        a, b, c, d, data = tt
        A = sheet_list[a]
        B = sheet_list[a + c - 1]
        A1 = '{}{}'.format(A, b + 1)
        B2 = '{}{}'.format(B, b + d)
        sheet.merge_cells('{}:{}'.format(A1, B2))
        sheet['{}'.format(A1)] = data

    book.save(output_path)
